package com.red.wine.ui;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baidu.mapapi.utils.h;
import com.baidu.platform.comapi.map.l;
import com.google.json.Gson;
import com.google.json.JsonParseException;
import com.red.wine.R;
import com.red.wine.WineApp;
import com.red.wine.adapter.GalleryAdapter;
import com.red.wine.adapter.ImageAdapter;
import com.red.wine.adapter.TasteAdapter;
import com.red.wine.model.DataInfo;
import com.red.wine.model.Headers;
import com.red.wine.model.ReturnInfo;
import com.red.wine.model.TasteInfo;
import com.red.wine.model.TasteRequest;
import com.red.wine.model.TasteReturnData;
import com.red.wine.model.TopInfo;
import com.red.wine.util.IntentUtil;
import com.red.wine.util.PrefsUtils;
import com.red.wine.util.StringUtil;
import com.red.wine.view.MyScrollLayout;
import com.red.wine.view.OnViewChangeListener;
import com.red.wine.view.PointChoice;
import com.red.wine.webservice.ServiceAsynTask;
import com.red.wine.webservice.ServiceHelper;
import com.red.wine.webservice.ServiceHost;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.OnGestureListener;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.Gallery;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

public class TasteActivity extends BaseActivity{
	private ImageView back;
	private Context context;
	// 屏幕宽度
	public static int screenWidth;
	// 屏幕高度
	public static int screenHeight;
	private ListView listview;
	private Gallery gallery;
	RelativeLayout layout;
	private TextView title;
//	TextView perode;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.taste_app_layout);
		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		screenHeight = metrics.heightPixels;
		screenWidth = metrics.widthPixels;
		title =(TextView) findViewById(R.id.taset_top_title_2);
		bitmap1 = BitmapFactory.decodeResource(getResources(), R.drawable.point_choice);
		bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.point_unchoice);
		point_layout = (RelativeLayout) findViewById(R.id.point_choice_layout);
		layout = (RelativeLayout) findViewById(R.id.taste_item_list_layout);
		listview = (ListView) findViewById(R.id.taste_listview_for_listsss);
		gallery = (Gallery) findViewById(R.id.taste_top_item_listview);
		back  = (ImageView) findViewById(R.id.taset_top_back_btn_2);
		back.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				finish();
			}
		});
		listview.setCacheColorHint(Color.TRANSPARENT);
		context = this;
		if(PrefsUtils.getIndex().equals("1")){
			title.setText("品 Taste");
		}else if(PrefsUtils.getIndex().equals("2")){
			title.setText("鉴 Appreciate");
		} 
		getData();
		
		listview.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				showLoading();
				Bundle bundle = new Bundle();
				bundle.putSerializable("info", data);
				bundle.putBoolean("fromsql", false);
				bundle.putInt("index", position);
				bundle.putSerializable("tasetinfo", null);
				IntentUtil.redirectToNext(context, TasteSecondActivity.class, bundle);
				hideLoading();
			}
		});
		gallery.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				showLoading();
				Bundle bundle = new Bundle();
				bundle.putSerializable("info", data);
				bundle.putBoolean("fromsql", false);
				bundle.putInt("index", arg2);
				bundle.putSerializable("tasetinfo", null);
				IntentUtil.redirectToNext(context, TasteSecondActivity.class, bundle);		
				hideLoading();
			}
		});
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			IntentUtil.redirectToNext(context, MainActivity.class);
			finish();
		}
		return super.onKeyDown(keyCode, event);
	}

	private void getData() {
		showLoading();
		new ServiceAsynTask<ReturnInfo>() {

			@Override
			protected ReturnInfo callService() throws IOException,
					JsonParseException, AssertionError {
				TasteRequest taste = new TasteRequest();
				Headers header = new Headers();
				header.setUa("ANDROID_HY/2.0.1.0 (customerid=gypsii, variant=gypsii),width=" + screenWidth);

				DataInfo data = new DataInfo();
				data.setNum(15);
				data.setSince_id(0);
				data.setCat(Integer.parseInt(PrefsUtils.getIndex()));
				Log.e("TAG", PrefsUtils.getIndex());
				// data.setCat(1);
				taste.cmd = "event_lists";
				taste.headers = header;
				taste.data = data;
				taste.sid = "";

				String up = new Gson().toJson(taste);
				String send = StringUtil.unicodeToUtf8("json=" + up);
				String urlstr = ServiceHost.getTasteURL();

				return ServiceHelper.getInstance().postData(urlstr, send,
						ReturnInfo.class);
			}

			@Override
			protected void runWithResult(ReturnInfo result) throws Exception {
				
				if (result != null) {
					bindData(result);
					Log.e("TAG", "isnotnull");
				} else {
					Log.e("TAG", "is null");
				}
				
			}

			@Override
			protected void runWithError(ReturnInfo result, int iErrorCode)
					throws Exception {
				Log.e("TAG", "异常" + iErrorCode);
				hideLoading();
				finish();
			}
		}.execute();
	}
//	RelativeLayout layout;
	private TopInfo topInfo;
	private List<TasteInfo> listData;
	private TopInfo topData;
	private List<TasteInfo> listTopdata;;
	ImageAdapter imgAdapter;
	TasteReturnData data;
	private TasteAdapter listadapter;
	protected void bindData(ReturnInfo returninfo) {
		if (returninfo != null && returninfo.getData() != null) {
			data = returninfo.getData();
		}
		if (data != null && data.getItems() != null) {
			listData = data.getItems();
		}
		listadapter= new TasteAdapter(context, listData);
		listview.setAdapter(listadapter);
		if(data != null && data.getTop() != null){
			topData = data.getTop();
		}
		if(topData != null && topData.getList() != null){
			listTopdata =topData.getList();
		}
		down();
	}
	List<Bitmap> bitmaps= new ArrayList<Bitmap>();
	List<Map<String, Bitmap>> dat= new ArrayList<Map<String,Bitmap>>();
	private void down() {
//		showLoading();
		for(int i = 0; i<listTopdata.size(); i++){
//			Log.e("TAG", "getThumbnail uri:= " + listTopdata.get(i).getThumbnail().get(0));
		}
		for (int i = 0; i < listTopdata.size(); i++) {
			Log.e("TAG", "已下载:= " + listTopdata.get(i).getThumbnail_m().get(0));
			if(!StringUtil.isEmptyOrNull(listTopdata.get(i).getThumbnail_m().get(0))){
				Bitmap bitmap = downImg(listTopdata.get(i).getThumbnail_m().get(0));
				Log.e("TAG", "bitmap: = " + bitmap.getHeight());
				bitmaps.add(bitmap);
			}

		}
		imgAdapter = new ImageAdapter(context, bitmaps);
		gallery.setAdapter(imgAdapter);
//		gallery.setPadding(0, 0,0 , bitmaps.get(0).getHeight()/2-5);
//		layout.setPadding(0, bitmaps.get(0).getHeight()/2+5 , 0, 0);
		hideLoading();
		Message message = new Message();
		message.what = 0x003;
		handler.sendMessage(message);
	
	}
	
	private RelativeLayout point_layout;
	
	private int images;
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			if(msg.what == 0x003){
				screenWidth = getWindow().getWindowManager().getDefaultDisplay()
						.getWidth();
				screenHeight = getWindow().getWindowManager().getDefaultDisplay()
						.getHeight();
				
				gallery.setVerticalFadingEdgeEnabled(false);// 取消竖直渐变边框
				gallery.setHorizontalFadingEdgeEnabled(false);// 取消水平渐变边框
				if(gallery != null && gallery.getAdapter() != null && gallery.getAdapter().getCount() > 0){
					images = gallery.getAdapter().getCount();
				}
				
				gallery.setOnItemSelectedListener(new OnItemSelectedListener() {

					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int position, long arg3) {
						if(gallery.getAdapter().getCount() > 0){
							if(point_layout.getChildCount() > 0){
								point_layout.removeAllViews();
							}
						}
						if(gallery.getAdapter().getCount() > 0){
							setChoicePointBit(position);
						}
					}

					public void onNothingSelected(AdapterView<?> arg0) {
						
					}
				});
				hideLoading();
			}
		};
	};
	Bitmap bitmap,bitmap1;
	private void setChoicePointBit(int index){
		if (images % 2 == 0) {
			for (int i = 0; i < images; i++) {
				if (i <= images / 2) {
					if(index == i){
					PointChoice choice = new PointChoice(context, bitmap1, screenWidth / 2 - (images / 2 - i)*5 - (images / 2 - i) * bitmap.getWidth(), (bitmaps.get(0).getHeight()/2) -10);
					point_layout.addView(choice);
					}else{
						PointChoice choice = new PointChoice(context, bitmap, screenWidth / 2 - (images / 2 - i)*5 - (images / 2 - i) * bitmap.getWidth(), (bitmaps.get(0).getHeight()/2) -10);
						point_layout.addView(choice);
					}
				}else{
					if(index == i){
					PointChoice choice = new PointChoice(context, bitmap1, screenWidth / 2 + (images / 2 + (i-images / 2))*5 - (images / 2 - (i-images / 2)) * bitmap.getWidth(), (bitmaps.get(0).getHeight()/2) -10);
					point_layout.addView(choice);
					}else{
						PointChoice choice = new PointChoice(context, bitmap, screenWidth / 2 + (images / 2 + (i-images / 2))*5 - (images / 2 - (i-images / 2)) * bitmap.getWidth(), (bitmaps.get(0).getHeight()/2) -10);
						point_layout.addView(choice);
					}
				}
			}
		}else if(images == 1){
			 
		}else{
			for (int i = 0; i < images; i++) {
				if (i == (images + 1) / 2) {
					if(index == i){
					PointChoice choice = new PointChoice(context, bitmap1, screenWidth / 2 , (bitmaps.get(0).getHeight()/2)  * 4 / 5);
					point_layout.addView(choice);
					}else{
						PointChoice choice = new PointChoice(context, bitmap, screenWidth / 2 , (bitmaps.get(0).getHeight()/2)  * 4 / 5);
						point_layout.addView(choice);
					}
				}else if(i<=(images + 1) / 2){
					if(index == i){
					PointChoice choice = new PointChoice(context, bitmap1, screenWidth / 2 - ((images + 1) / 2 - i)*5 - ((images + 1) / 2 - i) * bitmap.getWidth(), (bitmaps.get(0).getHeight()/2) -10);
					point_layout.addView(choice);
					}else{
						PointChoice choice = new PointChoice(context, bitmap, screenWidth / 2 - ((images + 1) / 2 - i)*5 - ((images + 1) / 2 - i) * bitmap.getWidth(), (bitmaps.get(0).getHeight()/2)  -10);
						point_layout.addView(choice);
					}
				}else{
					if(index == i){
					PointChoice choice = new PointChoice(context, bitmap1, screenWidth / 2 + ((images + 1) / 2 + (i-(images + 1) / 2))*5 - ((images + 1) / 2 - (i-(images + 1) / 2)) * bitmap.getWidth(), (bitmaps.get(0).getHeight()/2) -10);
					point_layout.addView(choice);
					}else{
						PointChoice choice = new PointChoice(context, bitmap, screenWidth / 2 + ((images + 1) / 2 + (i-(images + 1) / 2))*5 - ((images + 1) / 2 - (i-(images + 1) / 2)) * bitmap.getWidth(), (bitmaps.get(0).getHeight()/2) -10);
						point_layout.addView(choice);
					}
				}
			}
			
		}
	}
	
	private Bitmap downImg(String imgurl) {
		// 启动一个后台线程
		// 这里下载数据
		Bitmap downBItmap = null;
		try {
			URL url = new URL(imgurl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.connect();
			InputStream is = conn.getInputStream();
			int length = (int) conn.getContentLength();
			if (length > 0) {
				if (length != -1) {
					byte[] imgData = new byte[length];
					byte[] temp = new byte[length];
					int readLen = 0;
					int destPos = 0;
					while ((readLen = is.read(temp)) > 0) {
						System.arraycopy(temp, 0, imgData, destPos, readLen);
						destPos += readLen;
					}
					downBItmap = BitmapFactory.decodeByteArray(imgData, 0,
							imgData.length);
				}
			} else {
				downBItmap = null;
			}
			is.close();
			conn.disconnect();
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return downBItmap;
	}

	@Override
	protected void onResume() {
		super.onResume();

	}
}
